//
//  ZTAlbumDetailViewController.m
//  XMLYFM
//
//  Created by dllo on 15/12/26.
//  Copyright © 2015年 zzl. All rights reserved.
//

#import "ZTAlbumDetailViewController.h"
#import "AppTools.h"
#import "ZTAlbumHeadView.h"
#import "ZTAlbumDetailTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "ZTTrackModel.h"
#import "ZTAlbumModel.h"
#import <UIButton+WebCache.h>
#import "ZHPlayViewController.h"
#import "ZHPlayButtonView.h"

#define WIDTH [[UIScreen mainScreen] bounds].size.width

#define HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface ZTAlbumDetailViewController () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *albumTableView;

@property (nonatomic, strong) NSMutableArray *allTrackArray;


@property (nonatomic, strong) ZTAlbumHeadView *tableHeadView;

@property (nonatomic, assign) CGFloat cellHeight;

@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, strong) UIImageView *backgroundImageView;

@property (nonatomic, strong) UIImageView *overImage;

@property (nonatomic, strong) UIView *blurView;

@property (nonatomic, strong) ZTAlbumModel *albumModel;

@property (nonatomic, strong) UIButton *favorBtn;// 收藏按钮


@end

@implementation ZTAlbumDetailViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self getData];
    
    if ([ZHPlayViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePlaying) {
        
        [[ZHPlayButtonView shareButton] startCircle];
    }
    if ([ZHPlayViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePaused) {
        
        [[ZHPlayButtonView shareButton] stopCircle];
        
    }
    [self.view bringSubviewToFront:self.messageView];
    self.messageView.center = CGPointMake(SCREEN_WIDTH_ZH/2,  SCREEN_HEIGHT_ZH *0.85);
    
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[ZHPlayButtonView shareButton].musicBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //背景
    self.backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT * 0.4)];
    self.backgroundImageView.backgroundColor = [UIColor clearColor];
    self.backgroundImageView.alpha = 0.5;
    [self.view addSubview:self.backgroundImageView];
    

    self.overImage = [[UIImageView alloc] initWithFrame:self.backgroundImageView.frame];
    self.overImage.image = [UIImage imageNamed:@"header_over@2x.png"];
    [self.backgroundImageView addSubview:self.overImage];
    
    
    
#pragma mark - 创建UITableView
    self.albumTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 20  - 44) style:UITableViewStylePlain];
    self.albumTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.albumTableView];
    // 协议
    self.albumTableView.dataSource = self;
    self.albumTableView.delegate = self;
    [self.albumTableView registerClass:[ZTAlbumDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    
    [ZHPlayButtonView shareButton].frame =CGRectMake(WIDTH * 0.4, HEIGHT - WIDTH * 0.2, WIDTH * 0.2, HEIGHT * 0.2);
    [self.view addSubview :[ZHPlayButtonView shareButton]];
    
#pragma mark - 设置headerView
    self.tableHeadView = [[ZTAlbumHeadView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT * 0.25)];
       
    self.tableHeadView.backgroundColor = [UIColor clearColor];
    self.albumTableView.tableHeaderView = self.tableHeadView;

    
#pragma mark - 设置左按钮
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0 , 20, 30);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[UIImage imageNamed:@"btn_back_n"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_h"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationController.navigationBar.translucent = YES;
    
    
    
    
   
    
    
    //初始化数组
    self.allTrackArray = [NSMutableArray array];
    self.currentPage = 1;
    
    [self getData];
    [self.albumTableView reloadData];


}
#pragma mark - 收藏按钮
- (void)favorBtnAction:(UIButton *)btn{
    
//    NSLog(@"====== %d",[[[ZHFMDB shareFMDB] selectAlbumIdData] containsObject:self.favorModel.albumId]);
//    if ([[ZHFMDB shareFMDB] selectAlbumIdData].count == 0) {
//        <#statements#>
//    }
    if (_favorModel.isCollected) {
        [[ZHFMDB shareFMDB] deleteByAlbumId:self.favorModel.albumId];
        [_favorBtn setTitle:@"收藏" forState:UIControlStateNormal];
        self.favorModel.isCollected = NO;
//        NSLog(@"sc");
        
    } else {
//        NSLog(@"self.favorModel.albumId = %@",self.favorModel.albumId);

        if ([self.favorModel.albumId integerValue] != 0) {
            
            [[ZHFMDB shareFMDB] insertAlbumData:self.favorModel];

//            NSLog(@"dd");
        }else {
            self.favorModel.albumId = self.albumId;
            self.favorModel.albumTitle = self.myTitle;
            self.favorModel.title = self.myTitle;
            self.favorModel.coverMiddle = @"dd";
            self.favorModel.intro = @"dd";
            self.favorModel.tracks = @"dd";
            [[ZHFMDB shareFMDB] insertAlbumData:self.favorModel];
            
        }
        [_favorBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
        
        self.favorModel.isCollected = YES;

    }
}

#pragma mark - 请求数据
-(void)getData
{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?position=2&albumId=%@&isAsc=true&device=iphone&title=%@&pageSize=20", self.albumId, self.currentPage, self.albumId, self.myTitle];
    
//    NSLog(@"sdffffff--%@",urlStr);
    [AppTools getDataWithURL:urlStr Block:^(id result) {
        
        
        self.albumModel = [ZTAlbumModel modelWithDictionary:[result objectForKey:@"album"]];
        
        self.navigationItem.title = self.albumModel.title;

        NSURL *urlBg = [NSURL URLWithString:self.albumModel.coverLarge];
        [self.backgroundImageView sd_setImageWithURL:urlBg placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
        
        NSURL *url = [NSURL URLWithString:self.albumModel.coverSmall];
        [self.tableHeadView.albumPic sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
        
        self.tableHeadView.authorName.text = self.albumModel.nickname;
        self.tableHeadView.albumDigest.text = self.albumModel.intro;
        self.tableHeadView.playCount.text = [NSString stringWithFormat:@"%ld",self.albumModel.playtimes];
        
        NSURL *urlImg = [NSURL URLWithString:self.albumModel.avatarPath];
        [self.tableHeadView.avatarBtn sd_setImageWithURL:urlImg forState:UIControlStateNormal];
        
        NSMutableDictionary *trackDic = [result objectForKey:@"tracks"];
        
        for (NSMutableDictionary *dic in [trackDic objectForKey:@"list"]) {
            
            ZTTrackModel *model = [ZTTrackModel modelWithDictionary:dic];
            
            [self.allTrackArray addObject:model];
            
        }
        
        [self.albumTableView reloadData];
        
        self.currentPage ++;
        
    } ErrorBlock:^(NSError *error) {
        
        
        
    }];
}




#pragma mark - playButton
-(void)buttonAction:(UIButton *)btn
{
    
    ZHPlayViewController *player = [ZHPlayViewController sharaMusicPlayer];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
    
    [self.view.window.rootViewController presentViewController:naVC animated:YES completion:^{
        
    }];
    
}


#pragma mark - 返回按钮方法
-(void)backButtonAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark - tableView协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allTrackArray.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZTAlbumDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    ZTTrackModel *model = [self.allTrackArray objectAtIndex:indexPath.row];
    
    cell.trackModel = model;
    
    self.cellHeight = cell.playCount.frame.origin.y + cell.playCount.frame.size.height + 10;
    
    return cell;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}




#pragma mark section头视图

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView  alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
    
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(headView.frame.origin.x + 20, headView.frame.origin.y + 10, 100, headView.frame.size.height - 10)];
    myLabel.backgroundColor = [UIColor clearColor];
    
    myLabel.text = [NSString stringWithFormat:@"共 %ld 集", (long)self.albumModel.tracks];

    [myLabel sizeToFit];
    [headView addSubview:myLabel];
    
    //收藏按钮
    _favorBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _favorBtn.frame = CGRectMake(SCREEN_WIDTH_ZH / 2 - 30, headView.frame.origin.y + 10, 80, headView.frame.size.height - 10);
    _favorBtn.backgroundColor = [UIColor clearColor];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_favorBtn];
    [_favorBtn.titleLabel setFont:[UIFont systemFontOfSize:15.f]];
    [_favorBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [headView addSubview:_favorBtn];
    if ([[ZHFMDB shareFMDB] selectAlbumIdData].count == 0) {
        [_favorBtn setTitle:@"收藏" forState:UIControlStateNormal];
//        NSLog(@"1");
        _favorModel.isCollected = NO;
    }else{
        if ([[[ZHFMDB shareFMDB] selectAlbumIdData] containsObject:_favorModel.albumId]) {
            [_favorBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
            _favorModel.isCollected = YES;
//            NSLog(@"2");
        }else{
             [_favorBtn setTitle:@"收藏" forState:UIControlStateNormal];
            _favorModel.isCollected = NO;
//            NSLog(@"3");
        }
        
    }
    [_favorBtn addTarget:self action:@selector(favorBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sortButton.frame = CGRectMake(headView.frame.size.width - 60, headView.frame.origin.y + 10 , 30, headView.frame.size.height - 10);
    sortButton.backgroundColor = [UIColor clearColor];
    [sortButton setTitle:@"排序" forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:13 weight:0];
    [sortButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sortButton addTarget:self action:@selector(sortAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:sortButton];
    
    
    return headView;
    
    
}



#pragma mark - 排序方法
-(void)sortAction:(UIButton *)btn
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:_allTrackArray];
    self.allTrackArray = [NSMutableArray array];
    for (NSInteger i = array.count - 1; i >= 0; i--) {
        [self.allTrackArray addObject:[array objectAtIndex:i]];
    }
    
    [self.albumTableView reloadData];
    
}


#pragma mark - 播放音乐跳转到播放页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    ZHPlayViewController *player = [ZHPlayViewController sharaMusicPlayer];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
    ZTTrackModel *sing = [self.allTrackArray objectAtIndex:indexPath.row];
    player.song_id = sing.trackId;
    player.allMusicArray = self.allTrackArray;
    player.indexRow = indexPath.row;
    [self presentViewController:naVC animated:YES completion:^{
        
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return HEIGHT * 0.06;
}

#pragma mark - scrollView协议方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.y < 0) {
        
        self.backgroundImageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT * 0.4 - scrollView.contentOffset.y);
        self.overImage.frame = self.backgroundImageView.bounds;
        
    }
    
    if (scrollView.contentOffset.y > 0) {
        
        self.backgroundImageView.frame = CGRectMake(0, - scrollView.contentOffset.y, WIDTH, HEIGHT * 0.4);
        
    }
    
    if (scrollView.contentOffset.y == 0) {
        
    }
    
    [self.view bringSubviewToFront:self.albumTableView];
    [self.view bringSubviewToFront:[ZHPlayButtonView shareButton]];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
